(() => {
  const topicsEl = document.getElementById('topics');
  const addTopicBtn = document.getElementById('addTopicBtn');
  const messagesEl = document.getElementById('messages');
  const formEl = document.getElementById('form');
  const inputEl = document.getElementById('input');
  const sendBtn = document.getElementById('sendBtn');
  const setUsernameBtn = document.getElementById('setUsernameBtn');
  const balanceBtn = document.getElementById('balanceBtn');
  const setKeyBtn = document.getElementById('setKeyBtn');
  const statusBtn = document.getElementById('statusBtn');
  const loadingIndicator = document.getElementById('loadingIndicator');
  const themeBtn = document.getElementById('themeBtn');

  // Theme Logic
  const savedTheme = localStorage.getItem('theme') || 'dark';
  document.documentElement.setAttribute('data-theme', savedTheme);
  updateThemeIcon(savedTheme);

  themeBtn.addEventListener('click', () => {
    const current = document.documentElement.getAttribute('data-theme');
    const next = current === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', next);
    localStorage.setItem('theme', next);
    updateThemeIcon(next);
  });

  function updateThemeIcon(theme) {
    themeBtn.textContent = theme === 'dark' ? '🌙' : '☀️';
  }

  // Copy / Selection UI elements
  const toggleSelectBtn = document.getElementById('toggleSelectBtn');
  const selectionTools = document.getElementById('selectionTools');
  const selectAllBtn = document.getElementById('selectAllBtn');
  const copySelectedBtn = document.getElementById('copySelectedBtn');
  const cancelSelectBtn = document.getElementById('cancelSelectBtn');

  let isSelectionMode = false;

  // 用户名相关元素
  const usernameModal = document.getElementById('usernameModal');
  const usernameForm = document.getElementById('usernameForm');
  const usernameInput = document.getElementById('usernameInput');

  // Stable client id to识别"我"的消息
  let clientId = localStorage.getItem('clientId');
  if (!clientId) {
    clientId = (crypto && crypto.randomUUID) ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`;
    localStorage.setItem('clientId', clientId);
  }

  // 用户名管理
  let username = localStorage.getItem('username');

  // 用户名输入处理
  usernameForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const inputUsername = usernameInput.value.trim();
    if (!inputUsername) {
      alert('请输入用户名');
      return;
    }
    username = inputUsername;
    localStorage.setItem('username', username);
    usernameModal.style.display = 'none';
    renderSystem(`欢迎 ${username} 进入聊天室！`);
  });

  // 检查是否已有用户名
  if (username) {
    usernameModal.style.display = 'none';
  }

  // 无论是否有用户名，都要加载话题
  (async () => {
    console.log('页面加载完成，开始初始化...');
    await loadTopics();
  })();

  // 设置用户名按钮
  setUsernameBtn.addEventListener('click', () => {
    usernameInput.value = username || '';
    usernameModal.style.display = 'block';
    usernameInput.focus();
  });

  const protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  const ws = new WebSocket(`${protocol}://${location.host}/ws`);

  // 话题和消息都使用服务端持久化
  let topics = [];
  let currentTopicId = localStorage.getItem('currentTopicId') || '';
  localStorage.setItem('currentTopicId', currentTopicId);

  let messageStore = {}; // 现在作为缓存使用，不再保存到localStorage

  async function loadMessages(topicId) {
    if (!topicId) return;
    try {
      const res = await fetch(`/api/messages?topicId=${encodeURIComponent(topicId)}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const messages = await res.json();
      messageStore[topicId] = Array.isArray(messages) ? messages : [];
    } catch (e) {
      console.error(`加载话题 ${topicId} 的消息失败：${e.message}`);
      messageStore[topicId] = [];
    }
  }

  async function loadTopics() {
    try {
      console.log('开始加载话题...');

      const res = await fetch('/api/topics');
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      topics = await res.json();
      console.log('获取到话题数据:', topics);

      if (!Array.isArray(topics)) topics = [];
      if (!currentTopicId || !topics.find(t => t.id === currentTopicId)) {
        currentTopicId = topics.length ? topics[0].id : '';
        localStorage.setItem('currentTopicId', currentTopicId);
      }
      console.log('当前话题ID:', currentTopicId);
      renderTopics();
      await loadMessages(currentTopicId);
      renderAll();
    } catch (e) {
      console.error('加载话题失败:', e);
      await renderSystem(`加载话题失败：${e.message}`);
    }
  }

  function renderTopics() {
    topicsEl.innerHTML = '';
    topics.forEach(t => {
      const li = document.createElement('li');
      li.className = t.id === currentTopicId ? 'active' : '';

      const nameSpan = document.createElement('span');
      nameSpan.textContent = t.name;
      nameSpan.className = 'topic-name';
      nameSpan.addEventListener('click', () => switchTopic(t.id));

      const deleteBtn = document.createElement('button');
      deleteBtn.textContent = '×';
      deleteBtn.className = 'delete-topic-btn';
      deleteBtn.title = '删除话题';
      deleteBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        deleteTopic(t.id);
      });

      li.appendChild(nameSpan);
      li.appendChild(deleteBtn);
      topicsEl.appendChild(li);
    });
  }

  async function switchTopic(id) {
    currentTopicId = id;
    localStorage.setItem('currentTopicId', currentTopicId);
    // Reset selection mode when switching topics
    exitSelectionMode();
    renderTopics();
    await loadMessages(currentTopicId);
    renderAll();
    await renderSystem(`已切换到话题：${getTopicName(currentTopicId)}`);
  }

  function getTopicName(id) {
    const t = topics.find(x => x.id === id); return t ? t.name : id;
  }

  async function deleteTopic(topicId) {
    if (!confirm('确定要删除这个话题吗？删除后将无法恢复，包括话题内的所有聊天记录。')) {
      return;
    }

    try {
      const res = await fetch(`/api/topics/${encodeURIComponent(topicId)}`, {
        method: 'DELETE'
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);

      // 从本地数组中移除
      topics = topics.filter(t => t.id !== topicId);
      delete messageStore[topicId];

      // 如果删除的是当前话题，切换到第一个话题
      if (currentTopicId === topicId) {
        currentTopicId = topics.length ? topics[0].id : '';
        localStorage.setItem('currentTopicId', currentTopicId);
        await loadMessages(currentTopicId);
      }

      renderTopics();
      renderAll();
      await renderSystem(`话题已删除`);
    } catch (e) {
      await renderSystem(`删除话题失败：${e.message}`);
    }
  }
  addTopicBtn.addEventListener('click', async () => {
    const name = prompt('请输入话题名称');
    if (!name) return;
    try {
      const res = await fetch('/api/topics', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name })
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const created = await res.json();
      topics.push(created);
      await switchTopic(created.id);
    } catch (e) {
      await renderSystem(`新增话题失败：${e.message}`);
    }
  });

  ws.addEventListener('open', async () => {
    await renderSystem('已连接到聊天室');
  });

  ws.addEventListener('message', async (ev) => {
    let payload = null;
    try {
      payload = JSON.parse(ev.data);
    } catch {
      // 兼容旧文本：作为其他用户消息显示
      await pushMessage('default', { role: 'user', content: String(ev.data), mine: false, timestamp: Date.now() });
      if (currentTopicId === 'default') renderAll();
      return;
    }
    const type = payload.type || 'user';
    const content = payload.content || '';
    const senderId = payload.senderId || '';
    const timestamp = payload.timestamp || Date.now();
    const topicId = payload.topicId || 'default';
    const msgUsername = payload.username || '';

    // 自己发的用户消息已在本地渲染，忽略回显避免重复
    if (type === 'user' && senderId === clientId) return;

    const role = type === 'assistant' ? 'assistant' : 'user';
    await pushMessage(topicId, { role, content, mine: false, timestamp, username: msgUsername });
    if (topicId === currentTopicId) renderAll();
  });

  ws.addEventListener('close', async () => {
    await renderSystem('连接已关闭');
  });

  ws.addEventListener('error', async () => {
    await renderSystem('连接出错');
  });

  formEl.addEventListener('submit', async (e) => {
    e.preventDefault();
    const text = inputEl.value.trim();
    if (!text) return;

    // 检查是否有用户名
    if (!username) {
      alert('请先输入用户名');
      usernameModal.style.display = 'block';
      usernameInput.focus();
      return;
    }

    // 显示loading效果，禁用发送按钮
    loadingIndicator.style.display = 'flex';
    sendBtn.disabled = true;
    inputEl.disabled = true;

    // 先本地渲染"我"的消息（包含用户名）
    await pushMessage(currentTopicId, { role: 'user', content: text, mine: true, timestamp: Date.now(), username: username });
    renderAll();

    // 通过 WS 广播给其他客户端（JSON消息）
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ type: 'user', content: text, senderId: clientId, topicId: currentTopicId, timestamp: Date.now(), username: username }));
    }

    inputEl.value = '';

    // 调用后端 API 获取助手回复并渲染
    try {
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: text })
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      const reply = (data && data.content) ? data.content : '未获取到回复内容';
      await pushMessage(currentTopicId, { role: 'assistant', content: reply, mine: false, timestamp: Date.now() });
      renderAll();
    } catch (err) {
      await renderSystem(`请求失败：${err.message}`);
    } finally {
      // 隐藏loading效果，恢复发送按钮
      loadingIndicator.style.display = 'none';
      sendBtn.disabled = false;
      inputEl.disabled = false;
      inputEl.focus();
    }
  });

  // 查看余额按钮
  balanceBtn.addEventListener('click', async () => {
    await renderSystem('正在查询余额...');
    try {
      const res = await fetch('/api/balance');
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      const text = typeof data === 'object' ? JSON.stringify(data, null, 2) : String(data);
      const md = `余额信息:\n\n\`\`\`json\n${text}\n\`\`\``;
      await pushMessage(currentTopicId, { role: 'assistant', content: md, mine: false, timestamp: Date.now() });
      renderAll();
    } catch (err) {
      await renderSystem(`查询失败：${err.message}`);
    }
  });

  // 设置密钥按钮
  setKeyBtn.addEventListener('click', async () => {
    const k = prompt('请输入 DEEPSEEK_API_KEY');
    if (!k) return;
    try {
      const res = await fetch('/api/config/key', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ key: k })
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      await renderSystem('密钥设置成功');
    } catch (e) {
      await renderSystem(`密钥设置失败：${e.message}`);
    }
  });

  // 页面初始化检查密钥状态
  (async () => {
    try {
      const res = await fetch('/api/config/key');
      if (!res.ok) return;
      const data = await res.json();
      if (!data.set) {
        await renderSystem('未检测到 API 密钥，请点击右上角"设置密钥"配置。');
      }
    } catch { }
  })();

  async function pushMessage(topicId, msg) {
    if (!topicId) return;

    // 先添加到本地缓存
    if (!messageStore[topicId]) messageStore[topicId] = [];
    messageStore[topicId].push(msg);

    // 系统消息不保存到数据库，只在前端显示
    if (msg.role === 'system') {
      return;
    }

    // 保存到服务端
    try {
      const res = await fetch('/api/messages/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          topicId: topicId,
          role: msg.role,
          content: msg.content,
          username: msg.username || '',
          mine: msg.mine || false,
          timestamp: msg.timestamp
        })
      });
      if (!res.ok) {
        console.error(`保存消息到服务端失败：HTTP ${res.status}`);
      }
    } catch (e) {
      console.error(`保存消息到服务端失败：${e.message}`);
    }
  }

  function renderAll() {
    messagesEl.innerHTML = '';
    const list = messageStore[currentTopicId] || [];
    list.forEach(({ id, role, content, mine, timestamp, username: msgUsername }) => {
      const li = document.createElement('li');
      li.className = `msg ${role} ${mine ? 'me' : ''}`.trim();
      li.dataset.id = id; // Store ID for selection

      // Checkbox for selection mode
      if (isSelectionMode && role !== 'system') {
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.className = 'msg-checkbox';
        checkbox.dataset.content = content;
        li.appendChild(checkbox);

        // Click list item to toggle checkbox
        li.addEventListener('click', (e) => {
          if (e.target !== checkbox && !e.target.closest('.bubble') && !e.target.closest('.meta')) {
            checkbox.checked = !checkbox.checked;
          }
        });
      }

      const meta = document.createElement('div');
      meta.className = 'meta';
      let who;
      if (role === 'assistant') {
        who = '🤖 AI助手';
      } else if (mine) {
        who = `👤 ${username || '我'}`;
      } else {
        who = `👤 ${msgUsername || '用户'}`;
      }

      const metaText = document.createElement('span');
      metaText.textContent = `${who} · ${formatTime(timestamp)}`;
      meta.appendChild(metaText);

      // Copy button (individual)
      if (role !== 'system') {
        const copyBtn = document.createElement('button');
        copyBtn.textContent = '📋';
        copyBtn.className = 'copy-btn';
        copyBtn.title = '复制内容';
        copyBtn.onclick = (e) => {
          e.stopPropagation();
          copyToClipboard(content);
        };
        meta.appendChild(copyBtn);
      }

      // 添加删除按钮（只有当消息有ID时才显示）
      if (id && role !== 'system') {
        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = '×';
        deleteBtn.className = 'delete-message-btn';
        deleteBtn.title = '删除消息';
        deleteBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          deleteMessage(id);
        });
        meta.appendChild(deleteBtn);
      }

      const bubble = document.createElement('div');
      bubble.className = 'bubble';
      if (role === 'assistant') {
        bubble.innerHTML = renderMarkdown(content);
      } else {
        bubble.textContent = content;
      }

      li.appendChild(meta);
      li.appendChild(bubble);
      messagesEl.appendChild(li);
    });
    try {
      messagesEl.scrollTo({ top: messagesEl.scrollHeight, behavior: 'smooth' });
    } catch {
      messagesEl.scrollTop = messagesEl.scrollHeight;
    }
  }

  async function deleteMessage(messageId) {
    if (!confirm('确定要删除这条消息吗？')) {
      return;
    }

    try {
      const res = await fetch(`/api/messages/${encodeURIComponent(messageId)}`, {
        method: 'DELETE'
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);

      // 从本地缓存中移除
      if (messageStore[currentTopicId]) {
        messageStore[currentTopicId] = messageStore[currentTopicId].filter(msg => msg.id !== messageId);
      }

      renderAll();
      await renderSystem('消息已删除');
    } catch (e) {
      await renderSystem(`删除消息失败：${e.message}`);
    }
  }

  async function renderSystem(text) {
    await pushMessage(currentTopicId, { role: 'system', content: text, mine: false, timestamp: Date.now() });
    renderAll();
  }

  function formatTime(ts) {
    const d = new Date(ts);
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    return `${hh}:${mm}`;
  }

  function renderMarkdown(md) {
    try {
      const html = marked.parse(md, { breaks: true });
      return DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });
    } catch {
      return md;
    }
  }

  // Copy / Selection Logic

  async function copyToClipboard(text) {
    // 优先尝试现代 API
    if (navigator.clipboard && navigator.clipboard.writeText) {
      try {
        await navigator.clipboard.writeText(text);
        showToast('已复制到剪贴板');
        return;
      } catch (err) {
        console.warn('navigator.clipboard failed, trying fallback:', err);
      }
    }

    // Fallback logic for insecure contexts (HTTP)
    try {
      const textArea = document.createElement("textarea");
      textArea.value = text;

      // Ensure it's not visible but part of the DOM
      textArea.style.position = "fixed";
      textArea.style.left = "-9999px";
      textArea.style.top = "0";
      document.body.appendChild(textArea);

      textArea.focus();
      textArea.select();

      const successful = document.execCommand('copy');
      document.body.removeChild(textArea);

      if (successful) {
        showToast('已复制到剪贴板');
      } else {
        throw new Error('execCommand failed');
      }
    } catch (err) {
      console.error('Copy failed:', err);
      alert('复制失败，请手动复制');
    }
  }

  function showToast(msg) {
    // Simple toast implementation
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = msg;
    document.body.appendChild(toast);
    setTimeout(() => {
      toast.classList.add('show');
      setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => document.body.removeChild(toast), 300);
      }, 2000);
    }, 10);
  }

  // Toggle Selection Mode
  toggleSelectBtn.addEventListener('click', () => {
    isSelectionMode = true;
    toggleSelectBtn.style.display = 'none';
    selectionTools.style.display = 'flex';
    renderAll();
  });

  // Cancel Selection Mode
  function exitSelectionMode() {
    isSelectionMode = false;
    toggleSelectBtn.style.display = 'inline-flex';
    selectionTools.style.display = 'none';
    renderAll();
  }

  cancelSelectBtn.addEventListener('click', exitSelectionMode);

  // Select All
  selectAllBtn.addEventListener('click', () => {
    const checkboxes = document.querySelectorAll('.msg-checkbox');
    const allChecked = Array.from(checkboxes).every(cb => cb.checked);
    checkboxes.forEach(cb => cb.checked = !allChecked);
    selectAllBtn.textContent = allChecked ? '全选' : '全不选';
  });

  // Copy Selected
  copySelectedBtn.addEventListener('click', () => {
    const checkboxes = document.querySelectorAll('.msg-checkbox:checked');
    if (checkboxes.length === 0) {
      alert('请先选择要复制的消息');
      return;
    }

    const selectedContent = Array.from(checkboxes).map(cb => {
      // Find the bubble content related to this checkbox
      // We stored content in dataset for easier access, but for assistant messages with markdown, 
      // we might want the raw markdown which is what we stored in dataset.content
      return cb.dataset.content;
    }).join('\n\n-------------------\n\n');

    copyToClipboard(selectedContent);
    exitSelectionMode();
  });

  // 系统状态相关功能
  const statusModal = document.getElementById('statusModal');
  const closeModal = document.querySelector('.close');
  const refreshStatusBtn = document.getElementById('refreshStatusBtn');

  // 显示系统状态模态框
  statusBtn.addEventListener('click', () => {
    statusModal.style.display = 'block';
    loadSystemStatus();
  });

  // 关闭模态框
  closeModal.addEventListener('click', () => {
    statusModal.style.display = 'none';
  });

  // 点击模态框外部关闭
  window.addEventListener('click', (event) => {
    if (event.target === statusModal) {
      statusModal.style.display = 'none';
    }
  });

  // 刷新状态
  refreshStatusBtn.addEventListener('click', () => {
    loadSystemStatus();
  });

  // 加载系统状态
  async function loadSystemStatus() {
    try {
      // 显示加载状态
      const loadingElements = [
        'cpuUsage', 'cpuCores', 'cpuModel',
        'memoryUsage', 'memoryUsed', 'memoryTotal',
        'diskUsage', 'diskUsed', 'diskTotal',
        'networkConnections', 'networkUptime'
      ];

      loadingElements.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
          element.textContent = '加载中...';
        }
      });

      // 设置进程列表加载状态
      const topProcessesElement = document.getElementById('topProcesses');
      if (topProcessesElement) {
        topProcessesElement.innerHTML = '<div class="process-loading">加载中...</div>';
      }

      const response = await fetch('/api/status');
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const status = await response.json();

      // 更新CPU信息
      document.getElementById('cpuUsage').textContent = status.cpu.usage.toFixed(1);
      document.getElementById('cpuCores').textContent = status.cpu.cores;
      document.getElementById('cpuModel').textContent = status.cpu.model || '未知';

      // 更新内存信息
      document.getElementById('memoryUsage').textContent = status.memory.usage.toFixed(1);
      document.getElementById('memoryUsed').textContent = formatBytes(status.memory.used);
      document.getElementById('memoryTotal').textContent = formatBytes(status.memory.total);

      // 更新进程信息
      updateTopProcesses(status.memory.topProcesses);

      // 更新硬盘信息
      document.getElementById('diskUsage').textContent = status.disk.usage.toFixed(1);
      document.getElementById('diskUsed').textContent = formatBytes(status.disk.used);
      document.getElementById('diskTotal').textContent = formatBytes(status.disk.total);

      // 更新网络信息
      document.getElementById('networkConnections').textContent = status.network.connections;
      document.getElementById('networkUptime').textContent = formatUptime(status.uptime);

      // 绑定查看所有进程按钮事件
      const viewAllProcessesBtn = document.getElementById('viewAllProcessesBtn');
      if (viewAllProcessesBtn) {
        // 添加新的事件监听器
        viewAllProcessesBtn.onclick = async () => {
          // 直接在这里处理弹窗逻辑
          const processModal = document.getElementById('processModal');
          if (processModal) {
            processModal.style.display = 'block';

            // 直接在这里加载进程数据
            const processTableBody = document.getElementById('processTableBody');

            // 设置加载状态
            if (processTableBody) processTableBody.innerHTML = '<tr><td colspan="4" class="loading">正在获取进程信息...</td></tr>';

            try {
              const response = await fetch('/api/processes');
              if (!response.ok) {
                throw new Error('获取进程信息失败');
              }

              const data = await response.json();
              const processes = data.processes || [];

              // 更新进程表格
              if (processTableBody) {
                let html = '';
                processes.forEach(process => {
                  html += `
                    <tr>
                      <td title="${process.name}">${process.name}</td>
                      <td>${process.pid}</td>
                      <td>${process.memory}</td>
                      <td>${process.usage.toFixed(1)}%</td>
                    </tr>
                  `;
                });
                processTableBody.innerHTML = html;
              }

            } catch (error) {
              console.error('加载进程信息失败:', error);
              if (processTableBody) processTableBody.innerHTML = '<tr><td colspan="4" class="loading">加载失败，请重试</td></tr>';
            }
          }
        };
      }

      // 绑定进程弹窗关闭按钮事件
      const closeProcessModal = document.getElementById('closeProcessModal');
      const closeProcessModalBtn = document.getElementById('closeProcessModalBtn');
      const refreshProcessesBtn = document.getElementById('refreshProcessesBtn');

      if (closeProcessModal) {
        closeProcessModal.onclick = () => {
          const processModal = document.getElementById('processModal');
          if (processModal) processModal.style.display = 'none';
        };
      }

      if (closeProcessModalBtn) {
        closeProcessModalBtn.onclick = () => {
          const processModal = document.getElementById('processModal');
          if (processModal) processModal.style.display = 'none';
        };
      }

      if (refreshProcessesBtn) {
        refreshProcessesBtn.onclick = () => {
          const viewAllProcessesBtn = document.getElementById('viewAllProcessesBtn');
          if (viewAllProcessesBtn) viewAllProcessesBtn.click();
        };
      }

      // 绑定进程弹窗外部点击关闭事件
      const processModal = document.getElementById('processModal');
      if (processModal) {
        processModal.onclick = (e) => {
          if (e.target === processModal) {
            processModal.style.display = 'none';
          }
        };
      }

    } catch (error) {
      console.error('加载系统状态失败:', error);

      // 显示错误信息
      const errorElements = [
        'cpuUsage', 'cpuCores', 'cpuModel',
        'memoryUsage', 'memoryUsed', 'memoryTotal',
        'diskUsage', 'diskUsed', 'diskTotal',
        'networkConnections', 'networkUptime'
      ];

      errorElements.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
          element.textContent = '加载失败';
        }
      });

      // 设置进程列表错误状态
      const topProcessesElement = document.getElementById('topProcesses');
      if (topProcessesElement) {
        topProcessesElement.innerHTML = '<div class="process-loading">加载失败</div>';
      }
    }
  }

  // 格式化字节数
  function formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  // 格式化运行时间
  function formatUptime(seconds) {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);

    if (days > 0) {
      return `${days}天 ${hours}小时 ${minutes}分钟`;
    } else if (hours > 0) {
      return `${hours}小时 ${minutes}分钟`;
    } else {
      return `${minutes}分钟`;
    }
  }

  // 更新占用内存最多的进程
  function updateTopProcesses(processes) {
    const container = document.getElementById('topProcesses');

    if (!processes || processes.length === 0) {
      container.innerHTML = '<div class="process-loading">暂无数据</div>';
      return;
    }

    let html = '';
    processes.forEach(process => {
      html += `
        <div class="process-item">
          <div class="process-name" title="${process.name}">
            ${process.name}
          </div>
          <div class="process-memory">${process.memory}</div>
          <div class="process-usage">${process.usage.toFixed(1)}%</div>
        </div>
      `;
    });

    container.innerHTML = html;
  }

  // ESC键关闭弹窗
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      const processModal = document.getElementById('processModal');
      if (processModal && processModal.style.display === 'block') {
        processModal.style.display = 'none';
      }
      const statusModal = document.getElementById('statusModal');
      if (statusModal && statusModal.style.display === 'block') {
        statusModal.style.display = 'none';
      }
    }
  });

})();